package com.example.dialoglibrary.adapter;


import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.dialoglibrary.R;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class DialogAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final LayoutInflater mInflater;
    private Context mContext;
    private List<String> mArrayList;

    public DialogAdapter(Context context, List<String> stringList) {
        mContext = context;
        mArrayList = stringList;
        mInflater = LayoutInflater.from(context);
    }

    public DialogAdapter(Context context, String[] mArray) {
        mContext = context;
        mArrayList = new ArrayList<>(Arrays.asList(mArray));
        mInflater = LayoutInflater.from(context);
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new DialogViewHolder(mInflater.inflate(R.layout.layout_common_dialog_item, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
        if (mArrayList == null || TextUtils.isEmpty(mArrayList.get(position))) {
            return;
        }
        DialogViewHolder viewHolder = (DialogViewHolder) holder;
        viewHolder.mTextView.setText(mArrayList.get(position));
        viewHolder.mLinearLayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mClickItemListener.onClickItem(position, mArrayList.get(position));
            }
        });
    }

    @Override
    public int getItemCount() {
        if (mArrayList != null && mArrayList.size() > 0) {
            return mArrayList.size();
        }
        return 0;
    }

    class DialogViewHolder extends RecyclerView.ViewHolder {

        private TextView mTextView;
        private LinearLayout mLinearLayout;

        DialogViewHolder(@NonNull View itemView) {
            super(itemView);

            mTextView = itemView.findViewById(R.id.tv_common_dialog_item);
            mLinearLayout = itemView.findViewById(R.id.ll_common_dialog_item);
        }
    }


    public interface OnClickItemListener {
        void onClickItem(int position, String message);
    }

    private OnClickItemListener mClickItemListener;

    public void setClickItemListener(OnClickItemListener onClickItemListener) {
        mClickItemListener = onClickItemListener;
    }

}
